package com.elder.business.service.impl;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.elder.business.domain.*;
import com.elder.business.mapper.*;
import com.elder.business.service.IMedicationRecordsService;
import com.elder.common.core.domain.AjaxResult;
import com.elder.common.core.page.TableDataInfo;
import com.elder.common.utils.DateUtils;
import com.elder.common.utils.StringNewUtils;
import com.elder.common.utils.bean.BeanUtils;
import com.elder.common.utils.uuid.SnowGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用药记录Service业务层处理
 * 
 * @author elder
 * @date 2024-04-11
 */
@Service
public class MedicationRecordsServiceImpl implements IMedicationRecordsService
{
    @Autowired
    private MedicationRecordsMapper medicationRecordsMapper;
    @Autowired
    private ElderlyInfoMapper elderlyInfoMapper;
    @Autowired
    private MemberInfoMapper memberInfoMapper;
    @Autowired
    private ApartmentRoomInfoMapper roomInfoMapper;
    @Autowired
    private ElderMedicatePalnMapper medicatePalnMapper;
    /**
     * 查询用药记录
     * 
     * @param id 用药记录主键
     * @return 用药记录
     */
    @Override
    public JSONObject selectMedicationRecordsById(Long id)
    {
        MedicationRecords v = medicationRecordsMapper.selectMedicationRecordsById(id);
        ElderlyInfo elderlyInfo = elderlyInfoMapper.getElderInfoByElderId(v.getElderId());
        if(Objects.isNull(elderlyInfo)){
            elderlyInfo = new ElderlyInfo();
        }
        JSONObject obj = new JSONObject();
        obj.put("medicationId", StringNewUtils.formatStr(v.getId()));
        obj.put("elderId", StringNewUtils.formatStr(v.getElderId()));
        obj.put("elderName", Objects.isNull(elderlyInfo.getElderName()) ? "" : elderlyInfo.getElderName());
        obj.put("drugName", v.getDrugName());
        obj.put("medicationTime", DateUtils.dateStrMIAO(v.getMedicationTime()));
        obj.put("notes", v.getNotes());
        obj.put("nurseName", v.getNurseName());
        return obj;
    }

    /**
     * 查询用药记录列表
     * 
     * @param medicationRecords 用药记录
     * @return 用药记录
     */
    @Override
    public List<MedicationRecords> selectMedicationRecordsList(MedicationRecords medicationRecords)
    {
        return medicationRecordsMapper.selectMedicationRecordsList(medicationRecords);
    }

    /**
     * 新增用药记录
     * 
     * @param medicationDTO 用药记录
     * @return 结果
     */
    @Override
    public int insertMedicationRecords(MedicationRecordsDTO medicationDTO)
    {
        MedicationRecords medicationRecords = new MedicationRecords();
        BeanUtils.copyProperties(medicationDTO, medicationRecords);
        medicationRecords.setId(SnowGenerator.getId());
        medicationRecords.setCreateTime(DateUtils.getLongTime());
        medicationRecords.setMedicationTime(DateUtils.getDateSeconds(medicationDTO.getMedicationTime()));
        medicationRecords.setUpdateTime(DateUtils.getLongTime());
        return medicationRecordsMapper.insertMedicationRecords(medicationRecords);
    }

    /**
     * 修改用药记录
     * 
     * @param medicationDTO 用药记录
     * @return 结果
     */
    @Override
    public int updateMedicationRecords(MedicationRecordsDTO medicationDTO)
    {
        MedicationRecords medicationRecords = new MedicationRecords();
        BeanUtils.copyProperties(medicationDTO, medicationRecords);

        medicationRecords.setMedicationTime(DateUtils.getDateSeconds(medicationDTO.getMedicationTime()));
        medicationRecords.setUpdateTime(DateUtils.getLongTime());
        return medicationRecordsMapper.updateMedicationRecords(medicationRecords);
    }

    /**
     * 批量删除用药记录
     * 
     * @param ids 需要删除的用药记录主键
     * @return 结果
     */
    @Override
    public int deleteMedicationRecordsByIds(Long[] ids)
    {
        return medicationRecordsMapper.deleteMedicationRecordsByIds(ids);
    }

    /**
     * 删除用药记录信息
     * 
     * @param id 用药记录主键
     * @return 结果
     */
    @Override
    public int deleteMedicationRecordsById(Long id)
    {
        return medicationRecordsMapper.deleteMedicationRecordsById(id);
    }

    @Override
    public TableDataInfo getMedicationRecordsList(String elderName, String drugName, String startTime,String endTime, Integer pageNum, Integer pageSize) {
       List<Long> elderIds = null;
       if(!StringNewUtils.isEmpty(elderName)){
           List<ElderlyInfo> elderList = elderlyInfoMapper.getElderList(elderName);
           if(CollectionUtils.isNotEmpty(elderList)){
               elderIds = elderList.stream().map(ElderlyInfo::getElderId).collect(Collectors.toList());
           }
       }
        //用餐时间处理
        Long daystartTime = null;
        Long dayendTime = null;
        if(!StringNewUtils.isEmpty(startTime)&& !StringNewUtils.isEmpty(endTime)){
            Long currentTime = DateUtils.getTargetDateSeconds(startTime);
            Long endCurrentTime = DateUtils.getTargetDateSeconds(endTime);
            daystartTime = DateUtils.getDayStartTime(currentTime);
            dayendTime = DateUtils.getDayEndTime(endCurrentTime);
        }
        //分页
        PageHelper.startPage(pageNum, pageSize);
        List<MedicationRecords> list = medicationRecordsMapper.getmedicationRecordsList(elderIds,drugName,daystartTime,dayendTime);
        PageInfo<MedicationRecords> pageInfo = new PageInfo<>(list);
        List<MedicationRecords> medicationList = pageInfo.getList();
        List<Long> elderIdList = medicationList.stream().map(MedicationRecords::getElderId).collect(Collectors.toList());
        List<ElderlyInfo> elderlyInfos = elderlyInfoMapper.getElderInfoByElderIds(elderIdList);
        Map<Long,String> elderMap = CollectionUtils.isEmpty(elderlyInfos)? new HashMap<>():elderlyInfos.stream().collect(Collectors.toMap(ElderlyInfo::getElderId, ElderlyInfo::getElderName));
        List<JSONObject> jsonObjects = medicationList.stream().map(v -> {
            JSONObject obj = new JSONObject();
            obj.put("medicationId", StringNewUtils.formatStr(v.getId()));
            obj.put("elderName", Objects.isNull(elderMap.get(v.getElderId())) ? "" : elderMap.get(v.getElderId()));
            obj.put("drugName", v.getDrugName());
            obj.put("medicationTime", DateUtils.dateStrMIAO(v.getMedicationTime()));
            obj.put("notes", v.getNotes());
            obj.put("nurseName", v.getNurseName());
            return obj;
        }).collect(Collectors.toList());
        TableDataInfo result = new TableDataInfo();
        result.setCode(200);
        result.setTotal(pageInfo.getTotal());
        result.setRows(jsonObjects);
        return result;
    }

    @Override
    public TableDataInfo getNurseElderList(Long userId, String elderName, Integer pageNum, Integer pageSize) {
        if(Objects.isNull(userId)){
            return new TableDataInfo();
        }
        MemberInfo member = memberInfoMapper.getMember(userId);
        List<Long> elderIdList = null;
        if(!StringNewUtils.isEmpty(elderName)){
            List<ElderlyInfo> elderList = elderlyInfoMapper.getElderList(elderName);
            if(CollectionUtils.isNotEmpty(elderList)){
                return new TableDataInfo().getResult(new ArrayList<>(),0L);
            }
            elderIdList = CollectionUtils.isEmpty(elderList) ? null: elderList.stream().map(ElderlyInfo::getElderId).collect(Collectors.toList());
        }
        //获取房间中的elderid
        List<ElderlyApartmentBeds> bedInfoList = roomInfoMapper.getRoomBedInfoByNurseId(member.getMemberId());
        List<Long> elderIds = bedInfoList.stream().filter(rel -> Objects.nonNull(rel.getElderId())).map(ElderlyApartmentBeds::getElderId).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(elderIdList)){
            //取获取房间中的elderid 的交集
            elderIds.retainAll(elderIdList);
        }
        if(CollectionUtils.isEmpty(elderIds)){
            return new TableDataInfo().getResult(new ArrayList<>(),0L);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<ElderlyInfo> list = elderlyInfoMapper.getElderInfoByElderIds(elderIds);
        PageInfo<ElderlyInfo> pageInfo = new PageInfo<>(list);
        List<ElderlyInfo> elderList = pageInfo.getList();
        List<Long> roomIds = elderList.stream().map(ElderlyInfo::getRoomId).collect(Collectors.toList());
        List<ApartmentRoomInfo> roomInfoList = roomInfoMapper.getApartmentRoomInfoByRoomIds(roomIds);
        Map<Long, String> roomMap = roomInfoList.stream().collect(Collectors.toMap(ApartmentRoomInfo::getRoomId, ApartmentRoomInfo::getRoomCode));
        List<JSONObject> returnList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(elderList)){
            returnList = elderList.stream().map(v->{
                JSONObject obj = new JSONObject();
                obj.put("elderId", StringNewUtils.formatStr(v.getElderId()));
                obj.put("elderImg",v.getElderImg());
                obj.put("elderGender",v.getElderGender());
                obj.put("elderName",v.getElderName());
                obj.put("roomCode",roomMap.get(v.getRoomId()));
                obj.put("isEatMedication",v.getIsEatMedication());
                obj.put("drugName",v.getDrugName());
                return obj;
            }).collect(Collectors.toList());
        }
        TableDataInfo data = new TableDataInfo();
        data.setCode(200);
        data.setMsg("success");
        data.setTotal(pageInfo.getTotal());
        data.setRows(returnList);
        return data;
    }

    /**
     * 获取当前时间段内，未完成的用药记录
     * @param userId
     * @param elderId
     * @param drugName
     * @param timeBucket morning noon afterNoon
     * @return
     */
    @Override
    @Transactional
    public AjaxResult nurseMedicationFinish(Long userId, Long elderId, String drugName, String timeBucket) {
        Long currentTime = DateUtils.getLongTime();
        Long startTime = DateUtils.getDayStartTime(currentTime);
        Long endTime = DateUtils.getDayEndTime(currentTime);
        Long currentStartTime = DateUtils.getCurrentMonthStartTime();
        Long currentEndTime = DateUtils.getCurrentMonthEndTime();
        ElderMedicatePaln paln = medicatePalnMapper.getElderMedicatePalnCurrentMonth(currentStartTime, currentEndTime, 1);
        if(Objects.isNull(paln)){
            return new AjaxResult(200,"201");
        }
        ElderMedicatePaln medicatePaln = medicatePalnMapper.getCurrentDayMedicatePaln(elderId, startTime, endTime,2);
        MedicationRecords medication = new MedicationRecords();
        medication.setId(SnowGenerator.getId());
        medication.setElderId(elderId);
        Long time = DateUtils.getLongTime();
        medication.setNotes(DateUtils.dateStrMIAO(time)+"吃药已完成记录");
        medication.setMedicationTime(time);
        switch (timeBucket){
            case "morning":
                if(StringNewUtils.isEmpty(medicatePaln.getMorning())){
                    return new AjaxResult(200,"201");
                }
                if(medicatePaln.getMorningFinish()!=0){
                    return new AjaxResult(200,"202");
                }
                medication.setDrugName(medicatePaln.getMorning());
                break;
            case "noon":
                if(StringNewUtils.isEmpty(medicatePaln.getNoon())){
                    return new AjaxResult(200,"201");
                }
                if(medicatePaln.getNoonFinish()!=0){
                    return new AjaxResult(200,"202");
                }
                medication.setDrugName(medicatePaln.getNoon());
                break;
            case "afterNoon":
                if(StringNewUtils.isEmpty(medicatePaln.getAfterNoon())){
                    return new AjaxResult(200,"201");
                }
                if(medicatePaln.getAfterNoonFinish()!=0){
                    return new AjaxResult(200,"202");
                }
                medication.setDrugName(medicatePaln.getAfterNoon());
                break;
            default:
                return new AjaxResult(200,"201");
        }
        medication.setCreateUserId(userId);
        MemberInfo member = memberInfoMapper.getMember(userId);
        medication.setNurseName(Objects.isNull(member)?"":member.getMemberName());
        medication.setCreateTime(time);
        medicationRecordsMapper.insertMedicationRecords(medication);
        medicatePalnMapper.updateMedicatePaln(timeBucket,medicatePaln.getId());
        return new AjaxResult(200,"200");
    }


}
